#include "SelectModelRenderPass.h"
#include <SEEdit/Descriptors/SelectActorDescriptor.h>
#include <SERender/Renderer/Renderer.h>
#include <SEEdit/Render/RenderFeature/DebugRenderFeature.h>
#include <SEngine/Render/RenderFeature/ModelRenderFeature.h>
#include <SEngine/Ecs/Components/ModelRenderComp.h>
#include <SECore/Ecs/Actor.h>
#include <SECore/Manager.h>

namespace SEngine
{
    SelectModelRenderPass::SelectModelRenderPass(Renderer & renderer)
        : RenderPass(renderer)
    {
    }
    
    void SelectModelRenderPass::DrawFrame()
    {
        auto & modelRenderFeature = m_renderer.Descriptor<RenderFeature>::GetDescriptor<ModelRenderFeature>()->get();
        auto & debugFeature = m_renderer.Descriptor<RenderFeature>::GetDescriptor<DebugRenderFeature>()->get();
        auto & selectActorDes = m_renderer.AnyDescriptor::GetDescriptor<SelectActorDescriptor>()->get();
        if (selectActorDes.selectActor) {
            auto modelComp = selectActorDes.selectActor->get().GetComponent<ModelRenderComp>();
            if (!modelComp.has_value()) return;
            CurrentDrive().SetEnable(GraphicsEnum::STENCIL_TEST);
            CurrentDrive().SetClearStencil(0);
            CurrentDrive().SetStencilMask(0xFF);
            CurrentDrive().Clear(BufferType::STENCIL_BUFFER_BIT);
            CurrentDrive().SetStencilOp(GraphicsEnum::KEEP, GraphicsEnum::REPLACE, GraphicsEnum::REPLACE);
            CurrentDrive().SetStencilFunc(GraphicsEnum::ALWAYS, 1, 0xFF);
            CurrentDrive().SetColorMask(false, false, false, false);
            modelRenderFeature.DrawModel(modelComp->get().m_model, Manager::GetInstance().Get<Shader>("Unlit").value());
            CurrentDrive().SetColorMask(true, true, true, true);
            CurrentDrive().SetStencilOp(GraphicsEnum::KEEP, GraphicsEnum::KEEP, GraphicsEnum::KEEP);
            CurrentDrive().SetStencilFunc(GraphicsEnum::NOTEQUAL, 1, 0xFF);
            CurrentDrive().SetStencilMask(0x00);
            debugFeature.DrawContour(modelComp->get().m_model);
            CurrentDrive().SetDisable(GraphicsEnum::STENCIL_TEST);
        }
    }
} // namespace SEngine
